using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using AdminApiTemplate.Common.Helpers;
using AdminApiTemplate.Common.Models;
using AdminApiTemplate.Services.AdminUser;
using AdminApiTemplate.ThirdParty.Redis;
using System.Globalization;
using AdminApiTemplate.Common.Exceptions;

namespace AdminApiTemplate.Api.Controllers.BaseControllers
{
    /// <summary>
    /// 登录了即可访问的
    /// </summary>
    public class LogRequiredController : Controller
    {
        /// <summary>
        /// 执行前
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var requestId = RandomHelper.RequestId();
            var rsp = new ApiResponseBase<object>
            {
                ErrorCode = 999,
                ErrorMsg = "系统繁忙，请稍后再试",
                RequestId = requestId
            };

            var sk = context.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
            if (!SKHelper.Check(sk))
            {
                rsp.ReLogin=true;
                rsp.ErrorCode= (int)ErrorCodeEnum.NotAllowed;
                rsp.ErrorMsg="请重新登录";
                var json = JsonConvert.SerializeObject(rsp);
                context.Result = new ContentResult
                {
                    Content = json,
                    ContentType = "application/json",
                    StatusCode = 200,
                };
                return;
            }

            var parts = EncryptHelper.DESDecrypt(sk[0..^1], "1qaz2WSX");
            if (!DateTime.TryParseExact(parts.Substring(0, 14), "yyyyMMddHHmmss", null, DateTimeStyles.None, out var dt))
            {
                rsp.ReLogin=true;
                rsp.ErrorCode= (int)ErrorCodeEnum.NotAllowed;
                rsp.ErrorMsg="请重新登录";
                var json = JsonConvert.SerializeObject(rsp);
                context.Result = new ContentResult
                {
                    Content = json,
                    ContentType = "application/json",
                    StatusCode = 200,
                };
                return;
            }

            var ts = DateTime.Now - dt;
            if (ts.TotalHours>24)
            {
                rsp.ReLogin=true;
                rsp.ErrorCode= (int)ErrorCodeEnum.NotAllowed;
                rsp.ErrorMsg="请重新登录";
                var json = JsonConvert.SerializeObject(rsp);
                context.Result = new ContentResult
                {
                    Content = json,
                    ContentType = "application/json",
                    StatusCode = 200,
                };
                return;
            }

            var id = $"admin:{parts.Substring(20)}";
            var adminUser = RedisHelper.Get<CachedAdminUserDto>(id);
            if (adminUser == null)
            {
                rsp.ReLogin=true;
                rsp.ErrorCode= (int)ErrorCodeEnum.NotAllowed;
                rsp.ErrorMsg="请重新登录";
                var json = JsonConvert.SerializeObject(rsp);
                context.Result = new ContentResult
                {
                    Content = json,
                    ContentType = "application/json",
                    StatusCode = 200,
                };
                return;
            }

            AUID= adminUser.AUID;
            ChineseName = adminUser.ChineseName;
            EnglishName = adminUser.EnglishName;

            RedisHelper.Set(id, adminUser, TimeSpan.FromMinutes(30));
            base.OnActionExecuting(context);
        }

        public long AUID { get; set; } = 0;

        public string ChineseName { get; set; }

        public string EnglishName { get; set; }
    }
}
